package com.minsheng.epidemic_rep.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.io.*;
import java.util.List;

/**
 * @Classname GenerateCsv
 * @Description TODO
 * @Date 2020/9/27 10:08
 * @Created by You
 */
public class GenerateCsv {

    private static final  Logger logger = LoggerFactory.getLogger(GenerateCsv.class);

    /**
     * <生成csv文件>
     *
     * @param fileName    fileName
     * @param filePath    filePath
     * @param colNameList colNameList
     * @param dataList    dataList
     * @return filePath+fileName
     * @throws
     */
    public static String generateCsv(String filePath, String fileName,
                                     List<String> colNameList, List<List<String>> dataList)
            throws IOException
    {
        BufferedWriter csvWrite = null;
        String fileRealPath = filePath + fileName + ".csv";

        try
        {
            //定义文件类型
            File csvFile = new File(fileRealPath);

            //获取文件目录
            File parent = csvFile.getParentFile();
            if (!parent.exists())
            {
                parent.mkdirs();
            }

            //创建文件
            csvFile.createNewFile();
            csvWrite = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(csvFile), "GB2312"), 1024);

            //写入表头
            write(colNameList, csvWrite);
            //写入数据
            for (List<String> dataPerRow : dataList)
            {
                write(dataPerRow, csvWrite);
            }
            csvWrite.flush();

            return fileRealPath;
        }
        catch (IOException e)
        {
            logger.error("csv文件生成失败，原因：", e);
            throw new IOException("csv文件生成失败");
        }
        finally
        {

            try
            {
                if (null != csvWrite)
                {
                    csvWrite.close();
                }
            }
            catch (IOException e)
            {
                logger.error("关闭文件流失败，原因：", e);
                throw new IOException("关闭文件流失败");
            }
        }
    }

    /**
     *      * 将数据按行写入数据
     *      *
     *      * @param dataList
     *      * @param csvWreite
     *      * @throws IOException
     *      
     */
    private static void write(List<String> dataList, BufferedWriter csvWrite)
            throws IOException
    {
        for (String data : dataList)
        {
            StringBuffer buffer = new StringBuffer();
            String rowStr = buffer.append("\"").append(data).append("\",").toString();
            csvWrite.write(rowStr);
        }
        csvWrite.newLine();
    }

    /**
     * 批量删除文件
     *
     * @param fileRealPathList 文件绝对路径（带文件名）
     */
    public static void deleteFiles(List<String> fileRealPathList)
            throws IOException
    {
        if (!CollectionUtils.isEmpty(fileRealPathList))
        {
            File file = null;
            for (String fileRealPath : fileRealPathList)
            {
                file = new File(fileRealPath);
                if (file.exists() && file.isFile())
                {
                    file.delete();
                }
            }
        }
    }

}
